package com.yyh.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileOutputStream;

public class Demo5 {
    public static void main(String[] args) throws Exception {
        //1.创建User对象
        User user = new User("张三",18,"男",new String[]{"看电影","看小说"});
        //2.获取Jackson的操作对象
        ObjectMapper mapper = new ObjectMapper();
        //3.将user对象转为String
        String str = mapper.writeValueAsString(user);
        System.out.println(str);
        //4.将user对象写入文件
        mapper.writeValue(new File("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\JacksonUser.json"),user);
        //5.将user对象写入字节数组
        byte[] bytes = mapper.writeValueAsBytes(user);
        System.out.println(new String( bytes));
        //6.将json字符串：str转为User
        User user1 = mapper.readValue(str, User.class);
        System.out.println(user1);
        //7.将json文件中的json字符串读入程序中并转为User对象
        User user2 = mapper.readValue(new File("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\JacksonUser.json"), User.class);
        System.out.println(user2);
        //8.将字节数组bytes中的内容转为User对象
        User user3 = mapper.readValue(bytes, User.class);
        System.out.println(user3);
    }
}
